'use strict'

import { app, protocol, BrowserWindow, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
import { registerIpcHandlers } from './ipc'
import ProxyHandler from './ipc/proxy'

const { spawn } = require('child_process');

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  // { scheme: 'app', privileges: { secure: true, standard: true, stream: true } }
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let nodeServiceProcess;

async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 900,
    height: 650,
    frame: false,  // 移除默认框架
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
      nodeIntegrationInWorker: true
    }
  })

  // 添加关闭前的确认和清理
  win.on('close', async (e) => {
    e.preventDefault() // 阻止立即关闭
    try {
      await ProxyHandler.stopProxy()
    } catch (error) {
      console.error('清理代理时出错:', error)
    }
    // 强制退出应用
    app.quit()
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    win.setMenu(null)
    createProtocol('app')
    win.loadURL('app://./index.html')
  }

  // 监听窗口关闭事件
  win.on('closed', function () {
    // 结束 Node 服务进程
    app.quit();
  });
}

// 添加应用退出前的清理
app.on('before-quit', async (e) => {
  e.preventDefault()
  try {
    await ProxyHandler.stopProxy()
  } catch (error) {
    console.error('应用退出时清理代理出错:', error)
  }
  app.exit(0)
})

// 添加异常退出处理
process.on('uncaughtException', async (error) => {
  console.error('未捕获的异常:', error)
  try {
    await ProxyHandler.stopProxy()
  } catch (cleanupError) {
    console.error('清理代理时出错:', cleanupError)
  }
  app.exit(1)
})

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}


// 注册所有 IPC 处理程序
registerIpcHandlers()

ipcMain.handle('my-action', async (event, ...args) => {
  // 这里写 Node.js 处理逻辑
  try {
    // 示例：返回处理结果
    return { success: true, data: args }
  } catch (error) {
    return { success: false, error: error.message }
  }
})
